package com.learn.Util;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class AsyncConfig {

    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        // 设置核心线程池大小
        executor.setCorePoolSize(10);

        // 设置最大线程池大小
        executor.setMaxPoolSize(20);

        // 设置队列容量
        executor.setQueueCapacity(100);

        // 设置线程池中线程的名称前缀
        executor.setThreadNamePrefix("AsyncExecutor-");

        // 设置线程池中任务的等待时间，超过时间后将丢弃任务
        executor.setKeepAliveSeconds(60);

        // 设置线程池中线程的拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        // 初始化线程池
        executor.initialize();

        return executor;
    }
}
